using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.IO;
using CakeAnimation;

namespace CharacterAnimationEditor
{


    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        AnimationControlGUI controlGUI;
        PlayGUI playGui;
        OnionGUI onionGui;

        Context context = new Context();

        TimelineGui timeline;
        Animation anim;

        private IntPtr handle;
        //private GraphicsDeviceManager graphics;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }


        public Game1(IntPtr handle)
        {
            this.handle = handle;
            graphics = new GraphicsDeviceManager(this);
            graphics.PreparingDeviceSettings += OnPreparingDeviceSettings;
            Content.RootDirectory = "Content";

            this.IsMouseVisible = true;
        }

        private void OnPreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs args)
        {
            args.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = handle;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }


        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            context.ms = Mouse.GetState();
            context.mousePos = new Vector2(context.ms.X, context.ms.Y);
            context.ks = Keyboard.GetState();


            if (context.ks.IsKeyDown(Keys.LeftShift))
            {

                if (context.prevKs.IsKeyUp(Keys.F1) && context.ks.IsKeyDown(Keys.F1))
                {
                    AnimationSerializer serializer = new AnimationSerializer();
                    serializer.Save(context, anim, "1");
                }
            }


            if (context.ks.IsKeyDown(Keys.LeftControl))
            {
                if (context.ks.IsKeyDown(Keys.F1))
                {
                    AnimationSerializer serializer = new AnimationSerializer();
                    anim = serializer.LoadAnimation(context.AnimationContext, "1");
                    context.Animation = anim;

                    context.SelectedBone = null;
                    context.HoveredBone = null;
                }
            }

            timeline.Update(context);

            controlGUI.Update(context);

            context.CurrentKeyFrame.Pose.RootBone.UpdateTransform();

            playGui.Update(context);
            onionGui.Update(context);

            context.prevKs = context.ks;
            context.prevMs = context.ms;
            base.Update(gameTime);
        }

        public static float LerpAngle(float start, float end, float scale)
        {
            start = MathHelper.WrapAngle(start);
            end = MathHelper.WrapAngle(end);
            float delta = end - start;

            // If delta is not the shortest way, travel in the opposite direction  
            if (delta > MathHelper.Pi)
            {
                return (MathHelper.WrapAngle(start - (MathHelper.TwoPi - delta) * scale));
            }
            else if (delta < -MathHelper.Pi)
            {
                return (MathHelper.WrapAngle(start + (MathHelper.TwoPi + delta) * scale));
            }

            // No special case needed  
            return (start + delta * scale);
        }

        private Vector2 ParseVector2(string p)
        {
            return new Vector2(float.Parse(p.Split()[0]), float.Parse(p.Split()[1]));
        }

        public void Draw(TimeSpan t)
        {
            GameTime gt = new GameTime(t,t,t,t);
            Draw(gt);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            context.DeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

            context.Sb.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None);

            Texture2D bg = context.Content.Load<Texture2D>("GroundBG");

            context.Sb.Draw(
                bg,
                Vector2.Zero,
                null,
                Color.White,
                0.0f,
                Vector2.Zero,
                1.0f,
                SpriteEffects.None,
                1.0f
                );

            if (context.prevKs.IsKeyDown(Keys.LeftShift))
            {
                context.Sb.DrawString(
                    context.FontBig,
                    "SAVE",
                    new Vector2(300, 200),
                    Color.Black);

            }

            if (context.prevKs.IsKeyDown(Keys.LeftControl))
            {
                context.Sb.DrawString(
                    context.FontBig,
                    "LOAD",
                    new Vector2(300, 200),
                    Color.Black);

            }


            controlGUI.Draw(context);
            playGui.Draw(context);
            onionGui.Draw(context);

            timeline.Draw(context);

            context.Sb.End();

            base.Draw(gameTime);
        }
    }
}
